package com.example.demoface.controller;


import com.alibaba.fastjson2.JSON;
import com.example.demoface.domian.User;
import com.example.demoface.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/user/queryuserbytoken")
    public Object queryuserbytoken(@RequestParam String token) {
        Object o1 = redisTemplate.opsForValue().get("token:" + token);
        if (o1 != null){ // 查询成功
            return o1;
        }
        else {
            return null;
        }

    }



    @GetMapping("/user/querybyuserid")
    public Map queryByUserId(@RequestParam String userId, @RequestHeader(value = "Authorization", required = false) String authHeade) {
        Object o = redisTemplate.opsForValue().get("token:" + authHeade);//token:MTIzNDU2Nzg5MA==
        if(o != null) { // 查询成果
            User user = userService.selectOneById(userId);
            JSON.toJSONString(user);
            HashMap<Object, Object> res = new HashMap<>();
            res.put("msg","success");
            res.put("data",user);
            return  res;
        }
        else {  // 查询不成功
            HashMap<Object, Object> res = new HashMap<>();
            res.put("msg","error");
            res.put("data","登录已过期，请重新登录");
            return  res;

        }


    }


    @GetMapping("/user/querybydeptid")
    public List<User> query(User user) {
        List<User> users = userService.selectUser(user);

        return  users;
    }

    @GetMapping("/user/delete")
    public int delete(@RequestParam String  userId) {
        int i = userService.deleteByUserId(userId);
        return  i;
    }

    @GetMapping("/user/add")
    public int add(@RequestParam String  userId,@RequestParam String  userName) {
        User user = new User();
        user.setUserId(userId);

        user.setUserName(userName);
        return userService.insertUser(user);


    }
    @GetMapping("/user/addv2")
    public int addv2(@RequestBody User user) {
        return userService.insertUser(user);
    }


}
